<?php 

namespace app\seller\event;

use app\common\model\Coupon as CouponModel;
use app\common\utils\JsonService;

class CouponEvent{

    /*
    * 优惠劵列表
    */
    public static function couponList($params){
        //$params = array_filter(request()->param());
        $page = ! empty($params['page']) && $params['page'] >= 1 ? $params['page'] : 1;
        $where = [];
        if($id = isset($params['id'])){
                    $where[] = ['id','=',$params['id']];
            }
            if($name = isset($params['name'])){
                    $where[] = ['name','like',"%{$params['name']}%"];
            }
            if($create_num = isset($params['create_num'])){
                    $where[] = ['create_num','like',"%{$params['create_num']}%"];
            }
            if($send_num = isset($params['send_num'])){
                    $where[] = ['send_num','like',"%{$params['send_num']}%"];
            }
            if($use_num = isset($params['use_num'])){
                    $where[] = ['use_num','like',"%{$params['use_num']}%"];
            }
             $condition = [
            'where' => $where,
            'order' => ['id' => 'desc'],
                'paginate' => [
                'page' => $page,
                'query' => $params,
            ],
        ];
        $coupon = CouponModel::getPageAll($condition);
        return $coupon;
    }


    /*
    * 新增优惠劵
    */
    public static function createCoupon($data){
        $start_time = strtotime($data['use_start_time'].' 00:00:00');
        $end_time = strtotime($data['use_end_time'].' 23:59:59');
        if($end_time < $start_time){
            return JsonService::error('结束时间不能小于开始时间');
        }
        $data['use_start_time'] = $start_time;
        $data['use_end_time'] = $end_time;

        try {
            CouponModel::create($data);
        } catch (\Exception $ex) {
            return JsonService::error($ex->getMessage());
        }
        return JsonService::success();
    }

    /*
    * 更新优惠劵
    */
    public static function updateCoupon($data){
        $start_time = strtotime($data['use_start_time'].' 00:00:00');
        $end_time = strtotime($data['use_end_time'].' 23:59:59');
        if($end_time < $start_time){
            return JsonService::error('结束时间不能小于开始时间');
        }
        $data['use_start_time'] = $start_time;
        $data['use_end_time'] = $end_time;

        try {
            CouponModel::updateOne($data, ['id' => $data['id']]);
        } catch (\Exception $ex) {
            return JsonService::error($ex->getMessage());
        }
        return JsonService::success();
    }


}

